package com.avoscloud.chat.service;

import android.R.integer;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;

import com.avos.avoscloud.*;
import com.avoscloud.chat.avobject.User;
import com.avoscloud.chat.base.App;
import com.avoscloud.chat.base.C;
import com.avoscloud.chat.util.Logger;
import com.avoscloud.chat.util.PhotoUtils;
import com.avoscloud.chat.util.Utils;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * Created by lzw on 14-9-15.
 */
public class UserService {
	public static final int ORDER_UPDATED_AT = 1;
	public static final int ORDER_DISTANCE = 0;
	public static ImageLoader imageLoader = ImageLoader.getInstance();

	public static AVUser findUser(String id) throws AVException {
		AVQuery<AVUser> q = AVUser.getQuery(AVUser.class);
		q.setCachePolicy(AVQuery.CachePolicy.NETWORK_ELSE_CACHE);
		return q.get(id);
	}

	public static List<AVUser> findFriends() throws Exception {
		AVUser curUser = AVUser.getCurrentUser();
		AVQuery<AVUser> q = curUser.followeeQuery(AVUser.class);
		q.include("followee");//查询followee的所有相关数据
		final CountDownLatch latch = new CountDownLatch(1);
		final List<AVUser> friends = new ArrayList<AVUser>();
		final AVException[] es = new AVException[1];
		q.findInBackground(new FindCallback<AVUser>() {
			@Override
			public void done(List<AVUser> parseObjects,
					AVException parseException) {
				if (parseException != null) {
					es[0] = parseException;
				} else {
					friends.addAll(parseObjects);
				}
				latch.countDown();
			}
		});
		latch.await();
		if (es[0] != null) {
			throw es[0];
		} else {
			return friends;
		}
	}

	public static void displayAvatar(String imageUrl, ImageView avatarView) {
		imageLoader.displayImage(imageUrl, avatarView,
				PhotoUtils.avatarImageOptions);
	}

	public static void displayAvatar(AVUser user, ImageView avatarView) {
		if (user != null) {
			String avatarUrl = User.getAvatarUrl(user);
			if (TextUtils.isEmpty(avatarUrl) == false) {
				displayAvatar(avatarUrl, avatarView);
			}
		}
	}

	// 添加好友时查询用户
	public static List<AVUser> searchUser(String searchName, int skip)
			throws AVException {
		AVQuery<AVUser> q = AVUser.getQuery(AVUser.class);
		q.whereContains(User.USERNAME, searchName);// 根据输入框输入的用户名进行模糊搜索
		q.limit(C.PAGE_SIZE);// 限制每页显示十条，分页显示数据
		q.skip(skip);// 跳过首次查询的数据条数，实现分页
		AVUser user = AVUser.getCurrentUser();// 获取当前用户信息
		List<String> friendIds = new ArrayList<String>(
				CacheService.getFriendIds());// 获取已是用户好友的好友id
		friendIds.add(user.getObjectId());// 好友和用户本身的id集合
		q.whereNotContainedIn(C.OBJECT_ID, friendIds);// 查询的结果过滤掉了自己和已是自己好友的用户
		q.orderByDescending(C.UPDATED_AT);// 按更新时间降序排列
		// 查询的时候首先尝试从网络获取，如果失败，则从缓存中查找；是为了在没有网络的或者网络请求还没有足够时间完成的时候给用户一些数据
		q.setCachePolicy(AVQuery.CachePolicy.NETWORK_ELSE_CACHE);
		List<AVUser> users = q.find();// 按以上条件查找合适的用户
		CacheService.registerUsers(users);// 将查找的用户放入缓存中
		return users;
	}

	// 查询课程的评论
	public static List<AVObject> searchComment(String subjectId, int skip)
			throws AVException {
		List<AVObject> comment_list = new ArrayList<AVObject>();
		AVQuery<AVObject> avQuery = new AVQuery<AVObject>("comment");
		avQuery.whereEqualTo("comment_id", subjectId);// 根据输入框输入的用户名进行模糊搜索
		avQuery.limit(C.PAGE_SIZE);// 限制每页显示十条，分页显示数据
		avQuery.skip(skip);// 跳过首次查询的数据条数，实现分页

		avQuery.orderByDescending(C.UPDATED_AT);// 按更新时间降序排列
		try {
			comment_list = avQuery.find();

		} catch (AVException e) {
			Log.d("失败", "查询错误: " + e.getMessage());
		}

		return comment_list;
	}

	// 统计课程评论数
	public static int commentCount(String subjectId) throws AVException {
		AVQuery<AVObject> avQuery = new AVQuery<AVObject>("comment");
		avQuery.whereEqualTo("comment_id", subjectId);// 根据输入框输入的用户名进行模糊搜索
		int comment_length = avQuery.count();

		return comment_length;
	}

	// 查找用户所选的课程
	public static List<AVObject> searchUserCourse(String userId)
			throws AVException {
		List<AVObject> course_list = new ArrayList<AVObject>();
		AVQuery<AVObject> avQuery = new AVQuery<AVObject>("user_subject");
		avQuery.whereEqualTo("user_id", userId);// 根据输入框输入的用户名进行模糊搜索
		try {
			course_list = avQuery.find();

		} catch (AVException e) {
			Log.d("失败", "查询错误: " + e.getMessage());
		}

		return course_list;
	}

	// 根据课程id查找课程信息
	public static  List<AVObject> getCourseData(String subjectId)
			throws AVException {
	    List<AVObject> subject_list = new ArrayList<AVObject>();
		AVQuery<AVObject> avQuery = new AVQuery<AVObject>("subject");
		avQuery.whereEqualTo("objectId", subjectId);// 根据输入框输入的用户名进行模糊搜索
		subject_list = avQuery.find();

		return subject_list;
	}

	public static List<AVUser> findNearbyPeople(int orderType, int skip,
			int limit) throws AVException {
		PreferenceMap preferenceMap = PreferenceMap.getCurUserPrefDao(App.ctx);
		AVGeoPoint geoPoint = preferenceMap.getLocation();
		if (geoPoint == null) {
			Logger.i("geo point is null");
			return new ArrayList<AVUser>();
		}
		AVQuery<AVUser> q = AVObject.getQuery(AVUser.class);
		AVUser user = AVUser.getCurrentUser();
		q.whereNotEqualTo(C.OBJECT_ID, user.getObjectId());
		if (orderType == ORDER_DISTANCE) {
			q.whereNear(User.LOCATION, geoPoint);
		} else {
			q.orderByDescending(C.UPDATED_AT);
		}
		q.skip(skip);
		q.limit(limit);
		q.setCachePolicy(AVQuery.CachePolicy.NETWORK_ELSE_CACHE);
		List<AVUser> users = q.find();
		CacheService.registerUsers(users);
		return users;
	}

	public static void saveSex(User.Gender gender, SaveCallback saveCallback) {
		AVUser user = AVUser.getCurrentUser();
		User.setGender(user, gender);
		user.saveInBackground(saveCallback);
	}

	public static AVUser signUp(String name, String password)
			throws AVException {
		AVUser user = new AVUser();
		user.setUsername(name);
		user.setPassword(password);
		user.signUp();
		return user;
	}

	// 将头像地址和用户名保存到云端的file class中
	public static void saveAvatar(String path) throws IOException, AVException {
		AVUser user = AVUser.getCurrentUser();
		final AVFile file = AVFile.withAbsoluteLocalPath(user.getUsername(),
				path);
		file.save();
		user.put(User.AVATAR, file);

		user.save();
		user.fetch();
	}

	public static void updateUserInfo() {
		AVUser user = AVUser.getCurrentUser();
		if (user != null) {
			AVInstallation installation = AVInstallation
					.getCurrentInstallation();
			if (installation != null) {
				user.put(User.INSTALLATION, installation);
				user.saveInBackground();
			}
		}
	}

	public static void updateUserLocation() {
		PreferenceMap preferenceMap = PreferenceMap.getCurUserPrefDao(App.ctx);
		AVGeoPoint lastLocation = preferenceMap.getLocation();
		if (lastLocation != null) {
			final AVUser user = AVUser.getCurrentUser();
			final AVGeoPoint location = user.getAVGeoPoint(User.LOCATION);
			if (location == null
					|| !Utils.doubleEqual(location.getLatitude(),
							lastLocation.getLatitude())
					|| !Utils.doubleEqual(location.getLongitude(),
							lastLocation.getLongitude())) {
				user.put(User.LOCATION, lastLocation);
				user.saveInBackground(new SaveCallback() {
					@Override
					public void done(AVException e) {
						if (e != null) {
							e.printStackTrace();
						} else {
							Logger.v("lastLocation save "
									+ user.getAVGeoPoint(User.LOCATION));
						}
					}
				});
			}
		}
	}

	public static void addFriend(String friendId,
			final SaveCallback saveCallback) {
		AVUser user = AVUser.getCurrentUser();
		user.followInBackground(friendId, new FollowCallback() {
			@Override
			public void done(AVObject object, AVException e) {
				saveCallback.done(e);
			}
		});

	}

	public static void removeFriend(String friendId,
			final SaveCallback saveCallback) {
		AVUser user = AVUser.getCurrentUser();
		user.unfollowInBackground(friendId, new FollowCallback() {
			@Override
			public void done(AVObject object, AVException e) {
				saveCallback.done(e);
			}
		});
	}
}
